<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Redis;

class MediaStar extends Model
{
    protected $table = 'media_star';

    public function _media($uid = 0, $fields = []){
        return $this->belongsTo('App\Models\Media', 'media_id');
    }

    /*
     * 是否收藏
     * */
    public static function is_star_media($option_uid, $media_id)
    {
        if(!empty($option_uid) && !empty($media_id)){
            $key = 'media:star:m_'.$media_id.'_u_'.$option_uid;
            if(!empty(Redis::get($key)))
                return true;

            $rows = self::select('id')->where([['media_id', '=', $media_id], ['uid', '=', $option_uid]])->first();
            if(!empty($rows)){
                $expires_in = rand(3600, 3600*24);
                Redis::setex($key, $expires_in, 1);
                return true;
            }
        }
        return false;
    }

    /*
     * 设置视频收藏缓存
     * */
    public static function set_media_star($option_uid, $media_id, $type='add')
    {
        $key = 'media:star:m_'.$media_id.'_u_'.$option_uid;
        if($type == 'add'){
            $expires_in = rand(100*24*3600, 200*24*3600);
            Redis::setex($key, $expires_in, 1);
        }else{
            Redis::del($key);
        }
    }

}
